/**
 * @description 客服系统
 * @AUTH along
 * @DATA 2020-09-23
 */
export default class MessageSocket {
    constructor (context, object) {
        this.json = object || {};//参数
        this.context = context;//this
        this.ws = null;//socket对象
        this.socketUrl = '';//socket地址
        this.isHeartCheck = false;//是否开启心跳检测
        this.reConnectTime = 0;//断线重连间隔时间
        this.heartServerTimeout = null;//心跳检测定时器
        if(JSON.stringify(this.json) !== '{}') {
            this.isHeartCheck = this.json.isHeartCheck;
            this.socketUrl = object.socketUrl;
            this.reConnectTime = object.reConnectTime;
        }
        this.init();//初始化连接
    }

    init () {
        if(!Reflect.has(window, "WebSocket")) {
            this.context.$notify({
                title: '提示',
                message: '您的浏览器不支持WebSocket',
                type: 'warning',
                duration: 2000
            });
            return false;
        }
        if(!this.socketUrl) {
            this.context.$notify({
                title: '提示',
                message: 'WebSocket地址为空',
                type: 'warning',
                duration: 2000
            });
            return false;
        }

        this.ws = new WebSocket(this.socketUrl);
        this.eventListenerSocket();
        if(this.isHeartCheck) {
            //TODO 和后端约定
        }
    }

    eventListenerSocket () {
        this.ws.addEventListener('open', () => {
            //TODO 默认连接触发
            this.ws.send(JSON.stringify({
                cmd: 'stat',
                data: {
                    client_type: 2
                }
            }));
        });

        this.ws.addEventListener('message', evt => {
            this.monitorMessage(evt.data);
        });

        this.ws.addEventListener('error', evt => {
            console.log('连接异常', evt);
        });

        this.ws.addEventListener('close', evt => {
            this.context.commit('global/SET_READY_STATE', false);

            //断线重连
            clearTimeout(this.heartServerTimeout);
            this.heartServerTimeout = setTimeout(()=>{
                this.context.commit('global/RELINK_SOCKET', this.context.state.global.socket);
            }, this.reConnectTime);
            console.log('连接已关闭', evt);
        });
    }

    monitorMessage (data) {
        // console.log('----接收数据----', JSON.parse(data));
        const msg = JSON.parse(data);

        // 会话统计推送
        if(msg.tunnel == 'kf_server' && msg.event == 'session_stat') {
            //作延迟处理，比custom-list文件中获取慢点
            setTimeout(()=>{
                this.context.commit('global/SET_SESSION_STAT', msg.data);
            },100);
        }

        //消息撤回
        if(msg.tunnel == 'kf_server' && msg.event == 'retract_msg') {
            setTimeout(() => {
                this.context.commit('global/SET_MSG_RETRACT', JSON.stringify({
                    msg_id: msg.data.msg_id,
                    session_no: msg.data.session_no,
                    chat_no: msg.data.chat_no
                }));
            },100);
        }

        //消息接收
        if(msg.tunnel == 'kf_server' && msg.event == 'msg_receive') {
            setTimeout(()=>{
                let message = JSON.parse(JSON.stringify(msg));

                // console.log('--', message);

                if(message.data.msg_type == 'text') {
                    message.data.msg_content = JSON.parse(message.data.msg_content).text;
                }
                // this.context.commit('global/SET_DATALIST', [message.data]);
                this.context.commit('global/SET_DATALIST_TYPE', [message.data]);
                if(message.data.msg_type !== 'notice') {
                    this.context.commit('global/MESSAGE_NOTICE', message.data.msg_id + new Date().getTime());
                }
            },100);
        }

        //已读
        if(msg.tunnel == 'kf_server' && msg.event == 'msg_read') {
            setTimeout(()=>{
                if(msg.data.chat_no && !msg.data.msg_id) { //全部
                    this.context.commit('global/SET_READ', msg.data);
                }
                if(msg.data.chat_no && msg.data.msg_id) { //单条
                    this.context.commit('global/SET_READ_ONE', msg.data);
                }
            },300);
        }

        //转接会话通知
        if(msg.tunnel == 'kf_server' && msg.event == 'session_transfer_result') {
            setTimeout(()=>{
                this.context.commit('global/SET_SESSION_RESION', msg.data);
            },100);
        }

        //会话退出
        if(msg.tunnel == 'kf_server' && msg.event == 'session_quit') {
            setTimeout(()=>{
                this.context.commit('global/SESSION_QUIT', msg.data);
            },100);
        }

        //排队变动
        if(msg.tunnel == 'kf_server' && msg.event == 'queue_change') {
            setTimeout(()=>{
                this.context.commit('global/QUEUE_CHANGE', msg.data);
            },100);
        }

        // 订单消息通知
        if(msg.tunnel == 'kf_server' && msg.event == 'shop_order_create') {
            setTimeout(()=>{
                const value = Math.random().toString(36).slice(2);

                this.context.commit('global/SET_SHOP_ORDER_CREATE', value);
            },800);
        }
    }
}